import java.util.PriorityQueue;

//编写代码, 实现定时器案例
class MyTimerTask1 implements Comparable<MyTimerTask1>{
    private Runnable runnable;
    private long time;//时间最好用long
    public MyTimerTask1(Runnable runnable,long delay){
        this.runnable = runnable;
        this.time = delay+System.currentTimeMillis();
    }
    public void run(){
        runnable.run();
    }
    public long getTime(){
        return time;
    }
    @Override
    public int compareTo(MyTimerTask1 o) {
        return (int) (this.time-o.time);
    }
}
class MyTimer1{
    Object locker = new Object();
    private PriorityQueue<MyTimerTask1> queue = new PriorityQueue<>();
    public void schedule(Runnable runnable,long delay){
        synchronized (locker){
            MyTimerTask1 myTimerTask1 = new MyTimerTask1(runnable,delay);
            queue.offer(myTimerTask1);
            locker.notify();
        }
    }

    public MyTimer1(){
        Thread t = new Thread(()->{
            try {
                while (true){
                    //用循环不断获取系统时间
                    synchronized (locker){
                        if(queue.size()==0){
                            //没有东西
                            locker.wait();
                        }
                        MyTimerTask1 myTimerTask1 = queue.peek();
                        long time1 = System.currentTimeMillis();
                        if(time1>=myTimerTask1.getTime()){
                            //到时间了
                            myTimerTask1.run();
                            queue.poll();
                        }else{
                            //没到时间,等待
                            locker.wait(myTimerTask1.getTime()-time1);
                        }
                    }
                }
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        });
        t.start();
    }
}
public class Homework2 {
    public static void main(String[] args) {
        MyTimer1 myTimer1 = new MyTimer1();
        myTimer1.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("3000");
            }
        },3000);
        myTimer1.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("2000");
            }
        },2000);
        myTimer1.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("1000");
            }
        },1000);
    }
}
